package com.yeban.test1.utils;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;
import java.sql.*;

/**
 * @Desc TODO
 * @Author yeban
 * @Date 2025/11/18
 */
public class C3P0ByThreadLocalUtils {

    private static final ComboPooledDataSource pool = new ComboPooledDataSource("mysql");

    // 创建线程变量
    private static ThreadLocal<Connection> tl = new ThreadLocal<>();

    // 获取数据源
    public static DataSource getDataSource() {
        return pool;
    }

    // 获取连接对象
    public static Connection getConn() {
        Connection conn = tl.get();
        try {
            if (conn == null || conn.isClosed()) {
                conn = pool.getConnection();
                tl.set(conn);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return conn;
    }

    // 关闭资源
    public static void close() {
        Connection conn = tl.get();
        try {
            if (conn != null && !conn.isClosed()) {
                // 归还至连接池中
                conn.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            // 为了确保不会出现内存泄漏的问题
            tl.remove();
        }
    }

    public static void closeConn() {
        Connection conn = tl.get();
        try {
            if (conn != null && !conn.isClosed()) conn.close();
        } catch (Exception ignored) {}
        finally {
            tl.remove();
        }
    }


}
